'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 查询BOSS战当前状态
 * @author agl
 */

var async = require('async');
var _ = require('lodash');
var Code = require('../../../../consts/code');
var unionBossModel = require('../../../../models/unionBossModel.js');
var PlayerManager = require('../../../../libs/playerManager.js');

/**
 * 查询指定BOSS状态
 */
module.exports = function (msg, session, next) {
    var role_id = session.uid;
    var boss_id = msg.boss_id;

    var result = {};
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['role', 'role_union_boss'], cb);
            },
            function (cb) {
                var union_id = player_manager.role.union_id;
                if (union_id === 0) {
                    return next(null, {
                        code: Code.UNION_IS_NOT_JOIN
                    });
                }

                // 查询联盟BOSS信息
                unionBossModel.findById(union_id, cb);
            },
            function (model, cb) {
                var union_boss_model = model;
                var curr_boss_id = union_boss_model.curr_boss_id;
                var curr_boss_hp = union_boss_model.curr_boss_hp;
                if (boss_id > curr_boss_id) {
                    return next(null, {
                        code: Code.UNIOIN_BOSS_INVALID_BOSS_ID
                    });
                }

                result.boss_id = boss_id;
                if (boss_id === curr_boss_id && curr_boss_hp > 0) {
                    result.boss_hp = curr_boss_hp;
                    result.killker_name = '';
                    result.reward_status = 0;
                } else {
                    var killed_boss_info = union_boss_model.getKilledBossInfo(boss_id);
                    if (!killed_boss_info) {
                        return next(null, {
                            code: Code.UNIOIN_BOSS_INVALID_BOSS_ID
                        });
                    }

                    result.boss_hp = 0;
                    result.killer_name = killed_boss_info.killer_name;

                    var role_union_boss_model = player_manager.role_union_boss;
                    result.reward_status = role_union_boss_model.getRewardStatus(boss_id);
                }

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: result
            });
        }
    );
};
